package com.lenovo.nova.widget.dialog.buildview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.*;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.lenovo.nova.util.Applications;
import com.lenovo.nova.util.debug.mylog;
import com.lenovo.nova.util.graphics.FontUtil;
import com.lenovo.nova.utils.R;
import com.lenovo.nova.widget.GetViewMaxWidth;
import com.lenovo.nova.widget.dialog.BaseDialogFragment;

public class AdvanceDialogViewBuild implements DialogFragmentBuilder, android.view.View.OnClickListener {
    private static final String TAG = AdvanceDialogViewBuild.class.getSimpleName();
    ViewGroup rootView = null;
    View customView = null;
    BaseDialogFragment baseDialog;
    private TextView mTxViewMsg;
    private Button[] mBtns;
    int rootViewBackgroundWidth = 0;
    /**
     * user set the rootView width
     */
    private int rootViewWidth;

    public AdvanceDialogViewBuild(BaseDialogFragment baseDialog, Context context) {
        rootView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.layout_advance_dialog, null);
        mTxViewMsg = (TextView) rootView.findViewById(R.id.id_txview_scenic_util_dialog_msg);
        if (mBtns == null) {
            ViewGroup btnContainer = (ViewGroup) rootView.findViewById(R.id.id_llayout_scenic_util_btn_container);
            int count = btnContainer.getChildCount();
            mBtns = new Button[count];
            for (int i = 0; i < count; i++) {
                Button btn = (Button) btnContainer.getChildAt(i);
                btn.setOnClickListener(this);
                mBtns[i] = btn;
            }
        }

        if (mBtns.length == 3) {
            mBtns[0].setTag(DialogInterface.BUTTON_POSITIVE);
            mBtns[1].setTag(DialogInterface.BUTTON_NEUTRAL);
            mBtns[2].setTag(DialogInterface.BUTTON_NEGATIVE);
        }

        this.baseDialog = baseDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (customView != null) {
            ScrollView scrollView = (ScrollView) rootView.findViewById(R.id.id_scrollview_scenic_util_container);
            scrollView.removeAllViews();
            scrollView.addView(customView);

            //width decide
            View view = customView.findViewWithTag("nova_util_width_decision");
            if(view != null){
                int width = view.getLayoutParams().width;
                if(width > 0){
                    setRootViewWidth(width);
                }
            }
        }

        if(rootView.getBackground() == null){
//            rootView.setBackgroundResource(R.drawable.png_dialog_bg);
        }
//      rootView.startAnimation(AnimationUtils.loadAnimation(rootView.getContext(),R.anim.enter_scale));


        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if(rootViewWidth>0){
            //value the user what to
            internalSetRootViewWidth(rootViewWidth);
            mylog.i(TAG,"user decide the rootViewWidth : " + rootViewWidth);
        }else{
            calcRootViewMeasureIfNeed();
        }


        if(!Applications.get(rootView.getContext()).isInTouchMode()){
            for (Button btn : mBtns) {
                if(btn.getVisibility() == View.VISIBLE){
                    btn.requestFocus();
                    break;
                }

            }
        }

    }

    @Override
    public void onAttach(Activity activity) {
    }

    @Override
    public void onDetach() {
    }

    @Override
    public void setButton(int which, CharSequence msg, OnClickListener l) {
        for (Button btn : mBtns) {
            // the tag of btn is the identifier
            if ((Integer) btn.getTag() == which) {
                btn.setTag(which, l);
                btn.setText(msg);
                btn.setVisibility(View.VISIBLE);
                break;
            }
        }
    }

    @Override
    public void setView(View v) {
        customView = v;
    }

    @Override
    public void setTitle(CharSequence msg) {
        TextView txView = (TextView) rootView.findViewById(R.id.id_txview_scenic_util_dialog_title);
        txView.setVisibility(View.VISIBLE);
        txView.setText(msg);
    }

    @Override
    public void onClick(View v) {
        Integer which = (Integer) v.getTag();
        OnClickListener l = (OnClickListener) v.getTag(which);
        if (l != null) {
            l.onClick(baseDialog, which);
        }
    }

    @Override
    public void setMessage(CharSequence message) {
        mTxViewMsg.setText(message);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void setButtonBackground(int which, Drawable drawable) {
        for (Button btn : mBtns) {
            // the tag of btn is the identifier
            if ((Integer) btn.getTag() == which) {
                btn.setBackground(drawable);
                break;
            }
        }
    }

    public void setButtonFontType(int which, Typeface typeFace) {
        for (Button btn : mBtns) {
            // the tag of btn is the identifier
            if ((Integer) btn.getTag() == which) {
                btn.setTypeface(typeFace);
                break;
            }
        }
    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void setButtonsMarginTop(int top) {
        {
            if (top <= 0) {
                return;
            }
            ViewGroup group = (ViewGroup) rootView.findViewById(R.id.id_llayout_scenic_util_btn_container);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) group.getLayoutParams();
            params.removeRule(RelativeLayout.BELOW);
            params.topMargin = top;
        }

    }

    public void setButtonTextSizeAndColor(float size, int color) {
        if (size > 0) {
            for (int i = 0; i < mBtns.length; i++) {
                mBtns[i].setTextSize(size);
                mBtns[i].setTextColor(color);
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void setTitleMargin(int left, int top, int right, int bottom) {
        TextView txView = (TextView) rootView.findViewById(R.id.id_txview_scenic_util_dialog_title);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) txView.getLayoutParams();
        params.removeRule(RelativeLayout.BELOW);
        if (top >= 0) {
            params.topMargin = top;
        }
        if (left >= 0) {
            params.leftMargin = left;
        }

        if (right >= 0) {
            params.rightMargin = right;
        }
        if (bottom >= 0) {
            params.bottomMargin = bottom;
        }


    }

    public AdvanceDialogViewBuild setMessageViewGravity(int gravity){
        mTxViewMsg.setGravity(gravity);
        return this;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public AdvanceDialogViewBuild setMessageViewInCenter(boolean center){
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rootView.findViewById(R.id.id_scrollview_scenic_util_container).getLayoutParams();
        if(center){
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
        }else {
            params.removeRule(RelativeLayout.CENTER_IN_PARENT);
        }
        RelativeLayout.LayoutParams btnContainerParam = (RelativeLayout.LayoutParams) rootView.findViewById(R.id.id_llayout_scenic_util_btn_container).getLayoutParams();

        btnContainerParam.addRule(RelativeLayout.BELOW,R.id.id_scrollview_scenic_util_container);

        return this;
    }

    public AdvanceDialogViewBuild setMessageViewFontType(Typeface type){
        mTxViewMsg.setTypeface(type);
        return this;
    }

    public AdvanceDialogViewBuild setMessageViewFontType(String assetFontPath){
        FontUtil.createTypeface(mTxViewMsg, assetFontPath);
        return this;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public AdvanceDialogViewBuild setMessageViewBackgroud(Drawable backgroud){
        mTxViewMsg.setBackground(backgroud);
        return this;
    }

    public AdvanceDialogViewBuild setMessageViewBackgroudRes(int resId){
        mTxViewMsg.setBackgroundResource(resId);
        return this;
    }

    public AdvanceDialogViewBuild setMessageViewTextSizeAndColor(float size, int color) {
        mTxViewMsg.setTextSize(size);
        mTxViewMsg.setTextColor(color);
        return this;
    }

    public ViewGroup getRootView() {
        return rootView;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void setMessageMarginTop(int marginTop) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rootView.findViewById(R.id.id_scrollview_scenic_util_container).getLayoutParams();
        params.removeRule(RelativeLayout.BELOW);
        params.topMargin = marginTop;

    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public AdvanceDialogViewBuild setBackGround(Drawable background) {
        rootView.setBackground(background);
        return this;
    }

    public void setRootViewWidth(int width) {
//        rootView.getLayoutParams().width = width;
        this.rootViewWidth = width;
    }

    public Button[] getButtons() {
        return mBtns;
    }

    public ViewGroup getButtonsContainer(){
        return (ViewGroup) rootView.findViewById(R.id.id_llayout_scenic_util_btn_container);
    }

    public ViewGroup.MarginLayoutParams getButtonsContainerLayoutParam(){
        return (ViewGroup.MarginLayoutParams) getButtonsContainer().getLayoutParams();
    }


    public ViewGroup getMessageViewContainer(){
        return (ViewGroup) rootView.findViewById(R.id.id_scrollview_scenic_util_container);
    }

    public ViewGroup.MarginLayoutParams getMessageViewContainerParams(){
        return (ViewGroup.MarginLayoutParams) getMessageViewContainer().getLayoutParams();
    }

    private void internalSetRootViewWidth(int width){
        rootView.getLayoutParams().width = width;
    }

    private void calcRootViewMeasureIfNeed() {
        rootView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                rootView.getViewTreeObserver().removeOnPreDrawListener(this);

                Drawable rootViewBackGround = rootView.getBackground();
                if (rootViewBackGround != null) {
                    rootViewBackgroundWidth = rootView.getBackground().getIntrinsicWidth();
                    mylog.i(TAG, "backGroundWidht " + rootViewBackgroundWidth);
                }

                int rootViewWidth = rootView.getWidth();
                mylog.i(TAG, "rootViewWidth " + rootViewWidth);
                if(customView == null){
                    if(rootViewBackgroundWidth > rootViewWidth){
                        internalSetRootViewWidth(rootViewBackgroundWidth);
                    }
                }else{
                    mylog.i(TAG,"customView " + customView );
                    int customViewWidth = customView.getWidth();
                    int customViewBackgroundWidth = new GetViewMaxWidth().getMaxWidthByBackground(customView);

                    mylog.i(TAG,"customView width " + customViewWidth + "  customViewBackgroundWidth " + customViewBackgroundWidth);

                    if(customViewWidth > rootViewWidth ||
                            customViewBackgroundWidth > rootViewWidth || rootViewBackgroundWidth > rootViewWidth){
                        internalSetRootViewWidth(
                                Math.max(rootViewBackgroundWidth,
                                        Math.max(customViewBackgroundWidth,customViewWidth)));
                    }
                }
                return false;
            }
        });
    }


}